/**
 * 广寒宫
 * 网址:www.guanghangong.xyz
 */
package org.moon.framework.autoconfigure.thread;

import lombok.AllArgsConstructor;
import org.moon.framework.autoconfigure.thread.props.MoonAsyncProperties;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.aop.interceptor.SimpleAsyncUncaughtExceptionHandler;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurerSupport;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @Async 默认使用的线程池
 * @author moon
 */
@Configuration
@EnableAsync
@EnableScheduling
@AllArgsConstructor
@EnableConfigurationProperties(MoonAsyncProperties.class)
public class TaskExecutorAutoConfiguration extends AsyncConfigurerSupport {

	private final MoonAsyncProperties moonAsyncProperties;

	@Override
	@Bean(name = "taskExecutor")
	public Executor getAsyncExecutor() {
		ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
		executor.setCorePoolSize(moonAsyncProperties.getCorePoolSize());
		executor.setMaxPoolSize(moonAsyncProperties.getMaxPoolSize());
		executor.setQueueCapacity(moonAsyncProperties.getQueueCapacity());
		executor.setKeepAliveSeconds(moonAsyncProperties.getKeepAliveSeconds());
		executor.setThreadNamePrefix("async-executor-");
		// 传递线程变量
		executor.setTaskDecorator(MoonRunnableWrapper::new);
		executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
		return executor;
	}

	@Override
	public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
		return new SimpleAsyncUncaughtExceptionHandler();
	}
}